package com.tanhua.admin.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.commons.constants.LogType;
import com.tanhua.model.domain.Analysis;
import org.apache.ibatis.javassist.Loader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/5
 */
@Service
public class AnalysisService {
    @Autowired
    private AnalysisMapper analysisMapper;
    @Autowired
    private LogMapper logMapper;

    /**
     * 定时统计日志信息，保存到统计表
     */
    public void analysis() throws ParseException {
        //定义查询日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterdayStr = DateUtil.yesterday().toString("yyyy-MM-dd");
        //统计注册数量
        Integer numRegistered = logMapper.queryByTypeAndLogTime(LogType.USER_REGISTER, todayStr);
        //统计登录数量
        Integer numLogin = logMapper.queryByTypeAndLogTime(LogType.USER_LOGIN, todayStr);
        //统计活跃数量
        Integer numActive = logMapper.queryByLogTime(todayStr);
        //统计次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yesterdayStr);
        //根据日期查询统计数据
        LambdaQueryWrapper<Analysis> wrapper = new LambdaQueryWrapper<>();
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
        wrapper.eq(Analysis::getRecordDate, recordDate);
        Analysis analysis = analysisMapper.selectOne(wrapper);
        //更新/保存数据
        if (ObjectUtil.isEmpty(analysis)) {
            analysis = new Analysis();
            analysis.setRecordDate(recordDate);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(numLogin);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.insert(analysis);
        } else {
            analysis.setNumRegistered(numRegistered);
            analysis.setNumLogin(numLogin);
            analysis.setNumActive(numActive);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        }
    }
}
